import { t } from 'i18next'
import React, { useState } from 'react'
import { Alert } from '@/components/Alert'
import shallow from 'zustand/shallow'
import {
	DepartmentUser,
	pendingModelTranslator,
	selectedMtEntityTranslator,
	SelectedMtModel,
	Template,
	tempSelectedMtEntityTranslator,
} from '../../translator'
import { useMtAddStore } from '../../store'
import { useSelectedStore } from './store'
import { fetchTemplates, fetchUserExact } from '@/api/addMt'
import { useGlobalStore } from '@/store/global'

export const useSearch = () => {
	const { meetingType, isMcc, isSuperMeeting, maxRate, showTrees } = useMtAddStore(
		(state) => ({
			meetingType: state.meetingType,
			isMcc: state.isMcc,
			isSuperMeeting: state.isSuperMeeting,
			maxRate: state.maxRate,
			showTrees: state.showTrees,
		}),
		shallow
	)
	const addItem = useSelectedStore((state) => state.addItem)
	const [searchVal, setSearchVal] = useState('')
	const [actualSearchVal, setActualSearchVal] = useState('')
	const [searchError, setSearchError] = useState(false)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const placeholder =
		meetingType === 2
			? SWITCH.addMt.tip.email
				? t('请输入完整的帐号\\邮箱\\E164号码')
				: t('请输入完整的帐号\\E164号码')
			: SWITCH.addMt.tip.phone
			? SWITCH.addMt.tip.email
				? t('请输入完整的帐号\\邮箱\\E164号码\\电话号码\\IP地址')
				: t('请输入完整的帐号\\E164号码\\电话号码\\IP地址')
			: SWITCH.addMt.tip.email
			? t('请输入完整的帐号\\邮箱\\E164号码\\IP地址')
			: t('请输入完整的帐号\\E164号码\\IP地址')
	const fetchSearchDetail = async () => {
		let searchKey = actualSearchVal
		const [res, personal_templates] = await Promise.all([
			fetchUserExact(searchKey),
			showTrees.includes('template') ? fetchTemplates(searchKey) : Promise.resolve(undefined),
		])
		if (res) {
			//精确搜索，走左侧pending树实例化添加逻辑，因为有结果必在pending树里
			let data = res
			let _model = pendingModelTranslator(new DepartmentUser(data))
			_model.attr.fromSearchVal = searchKey
			let item = selectedMtEntityTranslator(_model, 'auto', { isMcc, isSuperMeeting, maxRate })
			addItem(new SelectedMtModel(item))
		} else if (personal_templates && personal_templates.length === 1) {
			//查找到了一个会议
			const data = personal_templates[0]
			let _model = pendingModelTranslator(new Template(data))
			_model.attr.fromSearchVal = searchKey
			let item = selectedMtEntityTranslator(_model, 'auto', { isMcc, isSuperMeeting, maxRate })
			addItem(new SelectedMtModel(item))
		} else {
			//未搜到人，建个临时账号
			let item = tempSelectedMtEntityTranslator(searchKey, { isMcc, isSuperMeeting, maxRate })
			addItem(new SelectedMtModel(item))
		}
	}
	const onKeyUp = (e: React.KeyboardEvent<Element>) => {
		if (e.keyCode == 13 || e.key === 'Enter') {
			if (searchError) {
				// Alert(`不能包含敏感字符 >'<"/`)
				Alert(t('不能包含敏感字符 >\'<"/'))
				return
			}
			if (actualSearchVal) {
				fetchSearchDetail()
			}
		}
	}
	const onChange = (e: React.ChangeEvent, val: string) => {
		if (val.match(/<|>|"|'|\//gi)) {
			setSearchError(true)
		} else {
			setSearchError(false)
		}
		setSearchVal(val)
		setActualSearchVal(val.trim())
	}
	const onAdd = () => {
		if (searchError) {
			Alert(t('不能包含敏感字符 >\'<"/'))
			return
		}
		if (actualSearchVal) {
			fetchSearchDetail()
		}
	}
	return [
		{ value: searchVal, actualSearchVal, placeholder, error: searchError },
		{ onKeyUp, onChange, onAdd },
	] as const
}
